package com.vdg.lockphotos.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.vdg.lockphotos.DisplayImageActivity;
import com.vdg.lockphotos.R;
import com.vdg.lockphotos.adapter.ImageSlideAdapter;
import com.vdg.lockphotos.app.ApplicationManagement;
import com.vdg.lockphotos.data.Photo;
import com.vdg.lockphotos.notify.OnLoadListHiddenImageListener;
import com.vdg.lockphotos.notify.OnSelectMenuItemListener;
import com.vdg.lockphotos.util.Utilities;
import com.vdg.lockphotos.view.CirclePageIndicator;
import com.vdg.lockphotos.view.PageIndicator;

public class HomeFragment extends Fragment {

	public static final String ARG_ITEM_ID = "home_fragment";

	private ViewPager mViewPager;
	TextView imgNameTxt;
	PageIndicator mIndicator;

	AlertDialog alertDialog;

	List<Photo> products = new ArrayList<Photo>();
	boolean stopSliding = false;
	String message;
	private FrameLayout mFrmDialog;
	private Handler handler;
	private int lastPosition;
	String url = null;
	private ImageSlideAdapter mImageSlideAdapter;
	private OnLoadListHiddenImageListener listener = new OnLoadListHiddenImageListener() {

		@Override
		public void onLoadSucessed(ArrayList<Photo> listPhoto) {
			// TODO Auto-generated method stub
			products.clear();
			products.addAll(listPhoto);
			if (products.size() != 0) {
				mImageSlideAdapter = new ImageSlideAdapter(activity, products,
						HomeFragment.this);
				mViewPager.setAdapter(mImageSlideAdapter);
				mFrmDialog.setVisibility(View.VISIBLE);
				mIndicator.setViewPager(mViewPager);
				mImageSlideAdapter.notifyDataSetChanged();
				imgNameTxt.setText(""
						+ ((Photo) products.get(mViewPager.getCurrentItem()))
								.getName());
				if (getPosition() < products.size()) {
					mViewPager.setCurrentItem(getPosition());
				} else {
					mViewPager.setCurrentItem(0);
				}
			} else {
				mImageSlideAdapter = new ImageSlideAdapter(activity, products,
						HomeFragment.this);
				mViewPager.setAdapter(mImageSlideAdapter);
				mFrmDialog.setVisibility(View.VISIBLE);
				mIndicator.setViewPager(mViewPager);
				mImageSlideAdapter.notifyDataSetChanged();
			}
			mFrmDialog.setVisibility(View.GONE);
			// Re-run callback
		}

		@Override
		public void onLoadFailed() {
			// TODO Auto-generated method stub
			mFrmDialog.setVisibility(View.GONE);
		}

		@Override
		public void onStartLoad() {
			// TODO Auto-generated method stub
			mFrmDialog.setVisibility(View.VISIBLE);
		}
	};
	private OnSelectMenuItemListener mListener = new OnSelectMenuItemListener() {

		@Override
		public void onSelectViewImage() {
			// TODO Auto-generated method stub
			if (products.size() == 0) {
				return;
			}
			Bundle arguments = new Bundle();
			Fragment fragment = null;
			Photo product = (Photo) products.get(mViewPager.getCurrentItem());
			arguments.putParcelable("singleProduct", product);

			// Start a new fragment
			fragment = new ProductDetailFragment();
			fragment.setArguments(arguments);

			FragmentTransaction transaction = activity
					.getSupportFragmentManager().beginTransaction();
			transaction.replace(R.id.content_frame, fragment,
					ProductDetailFragment.ARG_ITEM_ID);
			transaction.addToBackStack(ProductDetailFragment.ARG_ITEM_ID);
			transaction.commit();
			Log.v("debug", "onSelectViewImage");
		}

		@Override
		public void onSelectUnHide() {
			// TODO Auto-generated method stub
			if (Utilities.isExternalStorageReadable() == true
					&& Utilities.isExternalStorageWritable() == true) {
				if (products.size() == 0) {
					return;
				}
				ArrayList<Photo> listPhoto = new ArrayList<Photo>();
				listPhoto
						.add((Photo) products.get(mViewPager.getCurrentItem()));
				ApplicationManagement.getInstance(getActivity()).unHidePhotos(
						listPhoto);
				mFrmDialog.setVisibility(View.VISIBLE);
				if (mViewPager.getCurrentItem() > 0) {
					url = ((Photo) products
							.get(mViewPager.getCurrentItem() - 1))
							.getHiddenUrl();
				}
			} else {
				Utilities.showToast(
						getResources().getString(R.string.sdcard_notready),
						getActivity());
			}
		}
	};
	DisplayImageActivity activity;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity = (DisplayImageActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, container, false);
		findViewById(view);
		url = activity.getDisplayUrl();
		mIndicator.setOnPageChangeListener(new PageChangeListener());
		mViewPager.setOnPageChangeListener(new PageChangeListener());
		mViewPager.setOffscreenPageLimit(1);
		mViewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.getParent().requestDisallowInterceptTouchEvent(true);
				switch (event.getAction()) {

				case MotionEvent.ACTION_CANCEL:
					break;

				case MotionEvent.ACTION_UP:
					// calls when touch release on ViewPager
					if (products != null && products.size() != 0) {
						stopSliding = false;
					}
					break;

				case MotionEvent.ACTION_MOVE:
					// calls when ViewPager touch
					if (handler != null && stopSliding == false) {
						stopSliding = true;
					}
					break;
				}
				return false;
			}
		});
		ApplicationManagement.getInstance(getActivity()).loadHideImages(
				listener);
		return view;
	}

	private void findViewById(View view) {
		mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
		mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
		imgNameTxt = (TextView) view.findViewById(R.id.img_name);
		mFrmDialog = (FrameLayout) view.findViewById(R.id.frm_dialog);
	}

	private int getPosition() {
		for (int i = 0; i < products.size(); i++) {
			if (products.get(i).getHiddenUrl().equals(url)) {
				lastPosition = i;
				return i;
			}
		}
		return 0;
	}

	@Override
	public void onResume() {
		activity.regisOnSelectMenuListener(mListener);
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	public void showAlertDialog(String message, final boolean finish) {
		alertDialog = new AlertDialog.Builder(activity).create();
		alertDialog.setMessage(message);
		alertDialog.setCancelable(false);

		alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (finish)
							activity.finish();
					}
				});
		alertDialog.show();
	}

	private class PageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_IDLE) {
				if (products != null) {
					imgNameTxt
							.setText(""
									+ ((Photo) products.get(mViewPager
											.getCurrentItem())).getName());
				}
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

}